<template>
  <div class="club-create-container">
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">新增俱乐部</span>
          <div class="actions">
            <el-button @click="handleBack">
              <IconifyIconOffline icon="ep:back" class="mr-1" />
              返回
            </el-button>
          </div>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="club-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:info-filled" />
            基本信息
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="俱乐部名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入俱乐部名称"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="俱乐部简称" prop="shortName">
                <el-input
                  v-model="formData.shortName"
                  placeholder="请输入俱乐部简称"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="运动类型" prop="sportType">
                <el-select v-model="formData.sportType" placeholder="选择运动类型" style="width: 100%">
                  <el-option label="足球" value="football" />
                  <el-option label="篮球" value="basketball" />
                  <el-option label="羽毛球" value="badminton" />
                  <el-option label="乒乓球" value="table_tennis" />
                  <el-option label="网球" value="tennis" />
                  <el-option label="游泳" value="swimming" />
                  <el-option label="跑步" value="running" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="俱乐部等级" prop="level">
                <el-rate
                  v-model="formData.level"
                  :max="5"
                  show-text
                  :texts="['初级', '业余', '中级', '高级', '专业']"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="俱乐部LOGO" prop="logo">
            <div class="logo-upload">
              <el-upload
                class="logo-uploader"
                :show-file-list="false"
                :before-upload="beforeLogoUpload"
                :on-success="handleLogoSuccess"
                action="#"
                :auto-upload="false"
                :on-change="handleLogoChange"
              >
                <img v-if="formData.logo" :src="formData.logo" class="logo-preview" />
                <div v-else class="logo-placeholder">
                  <IconifyIconOffline icon="ep:plus" class="upload-icon" />
                  <div class="upload-text">上传LOGO</div>
                </div>
              </el-upload>
              <div class="upload-tip">
                <p>建议尺寸：200x200像素</p>
                <p>支持格式：JPG、PNG</p>
                <p>文件大小：不超过2MB</p>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item label="俱乐部介绍" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="4"
              placeholder="请输入俱乐部介绍"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <!-- 联系信息 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:phone" />
            联系信息
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactName">
                <el-input
                  v-model="formData.contactName"
                  placeholder="请输入联系人姓名"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                  v-model="formData.contactPhone"
                  placeholder="请输入联系电话"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="formData.email"
                  placeholder="请输入邮箱地址"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="微信号" prop="wechat">
                <el-input
                  v-model="formData.wechat"
                  placeholder="请输入微信号"
                  maxlength="30"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 地址信息 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:location" />
            地址信息
          </div>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="省份" prop="province">
                <el-select v-model="formData.province" placeholder="选择省份" style="width: 100%" @change="handleProvinceChange">
                  <el-option label="北京市" value="beijing" />
                  <el-option label="上海市" value="shanghai" />
                  <el-option label="广东省" value="guangdong" />
                  <el-option label="浙江省" value="zhejiang" />
                  <el-option label="江苏省" value="jiangsu" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="城市" prop="city">
                <el-select v-model="formData.city" placeholder="选择城市" style="width: 100%" @change="handleCityChange">
                  <el-option v-for="city in cityOptions" :key="city.value" :label="city.label" :value="city.value" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="8">
              <el-form-item label="区县" prop="district">
                <el-select v-model="formData.district" placeholder="选择区县" style="width: 100%">
                  <el-option v-for="district in districtOptions" :key="district.value" :label="district.label" :value="district.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入详细地址"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="场馆名称" prop="venue">
            <el-input
              v-model="formData.venue"
              placeholder="请输入主要活动场馆名称"
              maxlength="50"
            />
          </el-form-item>
        </div>
        
        <!-- 俱乐部设置 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:setting" />
            俱乐部设置
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最大成员数" prop="maxMembers">
                <el-input-number
                  v-model="formData.maxMembers"
                  :min="1"
                  :max="1000"
                  placeholder="请输入最大成员数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="入会费用" prop="joinFee">
                <el-input-number
                  v-model="formData.joinFee"
                  :min="0"
                  :precision="2"
                  placeholder="请输入入会费用"
                  style="width: 100%"
                >
                  <template #append>元</template>
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="加入方式" prop="joinType">
                <el-radio-group v-model="formData.joinType">
                  <el-radio value="free">自由加入</el-radio>
                  <el-radio value="approval">申请审核</el-radio>
                  <el-radio value="invite">邀请制</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="俱乐部状态" prop="status">
                <el-radio-group v-model="formData.status">
                  <el-radio value="active">正常</el-radio>
                  <el-radio value="disabled">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="其他设置">
            <el-checkbox-group v-model="formData.settings">
              <el-checkbox value="public">公开俱乐部</el-checkbox>
              <el-checkbox value="allowGuest">允许访客参观</el-checkbox>
              <el-checkbox value="needRealName">要求实名认证</el-checkbox>
              <el-checkbox value="autoApprove">自动通过申请</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </div>
        
        <!-- 认证信息 -->
        <div class="form-section">
          <div class="section-title">
            <IconifyIconOffline icon="ep:document" />
            认证信息
          </div>
          
          <el-form-item label="营业执照" prop="businessLicense">
            <div class="file-upload">
              <el-upload
                class="license-uploader"
                :show-file-list="false"
                :before-upload="beforeLicenseUpload"
                :on-success="handleLicenseSuccess"
                action="#"
                :auto-upload="false"
                :on-change="handleLicenseChange"
              >
                <el-button type="primary">
                  <IconifyIconOffline icon="ep:upload" class="mr-1" />
                  上传营业执照
                </el-button>
              </el-upload>
              <div v-if="formData.businessLicense" class="file-info">
                <IconifyIconOffline icon="ep:document" class="file-icon" />
                <span class="file-name">{{ formData.businessLicenseName }}</span>
                <el-button type="danger" link size="small" @click="removeLicense">
                  <IconifyIconOffline icon="ep:delete" />
                </el-button>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item label="法人身份证" prop="idCard">
            <div class="file-upload">
              <el-upload
                class="id-uploader"
                :show-file-list="false"
                :before-upload="beforeIdUpload"
                :on-success="handleIdSuccess"
                action="#"
                :auto-upload="false"
                :on-change="handleIdChange"
              >
                <el-button type="primary">
                  <IconifyIconOffline icon="ep:upload" class="mr-1" />
                  上传身份证
                </el-button>
              </el-upload>
              <div v-if="formData.idCard" class="file-info">
                <IconifyIconOffline icon="ep:document" class="file-icon" />
                <span class="file-name">{{ formData.idCardName }}</span>
                <el-button type="danger" link size="small" @click="removeIdCard">
                  <IconifyIconOffline icon="ep:delete" />
                </el-button>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item label="认证说明">
            <el-input
              v-model="formData.verifyRemark"
              type="textarea"
              :rows="3"
              placeholder="请输入认证说明或补充材料说明"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
        
        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button size="large" @click="handleBack">取消</el-button>
          <el-button type="primary" size="large" :loading="submitting" @click="handleSubmit">
            创建俱乐部
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type UploadProps } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";

const router = useRouter();

// 表单引用
const formRef = ref<FormInstance>();

// 状态
const submitting = ref(false);

// 表单数据
const formData = reactive({
  name: "",
  shortName: "",
  sportType: "",
  level: 3,
  logo: "",
  description: "",
  contactName: "",
  contactPhone: "",
  email: "",
  wechat: "",
  province: "",
  city: "",
  district: "",
  address: "",
  venue: "",
  maxMembers: 50,
  joinFee: 0,
  joinType: "free",
  status: "active",
  settings: ["public"],
  businessLicense: "",
  businessLicenseName: "",
  idCard: "",
  idCardName: "",
  verifyRemark: ""
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: "请输入俱乐部名称", trigger: "blur" },
    { min: 2, max: 50, message: "俱乐部名称长度在 2 到 50 个字符", trigger: "blur" }
  ],
  shortName: [
    { required: true, message: "请输入俱乐部简称", trigger: "blur" },
    { min: 1, max: 20, message: "俱乐部简称长度在 1 到 20 个字符", trigger: "blur" }
  ],
  sportType: [
    { required: true, message: "请选择运动类型", trigger: "change" }
  ],
  level: [
    { required: true, message: "请选择俱乐部等级", trigger: "change" }
  ],
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
    { min: 2, max: 20, message: "联系人姓名长度在 2 到 20 个字符", trigger: "blur" }
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ],
  province: [
    { required: true, message: "请选择省份", trigger: "change" }
  ],
  city: [
    { required: true, message: "请选择城市", trigger: "change" }
  ],
  district: [
    { required: true, message: "请选择区县", trigger: "change" }
  ],
  address: [
    { required: true, message: "请输入详细地址", trigger: "blur" },
    { min: 5, max: 100, message: "详细地址长度在 5 到 100 个字符", trigger: "blur" }
  ],
  maxMembers: [
    { required: true, message: "请输入最大成员数", trigger: "blur" },
    { type: "number", min: 1, max: 1000, message: "最大成员数必须在 1 到 1000 之间", trigger: "blur" }
  ],
  joinFee: [
    { required: true, message: "请输入入会费用", trigger: "blur" },
    { type: "number", min: 0, message: "入会费用不能为负数", trigger: "blur" }
  ],
  joinType: [
    { required: true, message: "请选择加入方式", trigger: "change" }
  ],
  status: [
    { required: true, message: "请选择俱乐部状态", trigger: "change" }
  ]
};

// 城市选项
const cityOptions = computed(() => {
  const cityMap: Record<string, Array<{label: string, value: string}>> = {
    beijing: [
      { label: "北京市", value: "beijing_city" }
    ],
    shanghai: [
      { label: "上海市", value: "shanghai_city" }
    ],
    guangdong: [
      { label: "广州市", value: "guangzhou" },
      { label: "深圳市", value: "shenzhen" },
      { label: "珠海市", value: "zhuhai" }
    ],
    zhejiang: [
      { label: "杭州市", value: "hangzhou" },
      { label: "宁波市", value: "ningbo" },
      { label: "温州市", value: "wenzhou" }
    ],
    jiangsu: [
      { label: "南京市", value: "nanjing" },
      { label: "苏州市", value: "suzhou" },
      { label: "无锡市", value: "wuxi" }
    ]
  };
  return cityMap[formData.province] || [];
});

// 区县选项
const districtOptions = computed(() => {
  const districtMap: Record<string, Array<{label: string, value: string}>> = {
    beijing_city: [
      { label: "朝阳区", value: "chaoyang" },
      { label: "海淀区", value: "haidian" },
      { label: "西城区", value: "xicheng" }
    ],
    shanghai_city: [
      { label: "浦东新区", value: "pudong" },
      { label: "黄浦区", value: "huangpu" },
      { label: "徐汇区", value: "xuhui" }
    ],
    guangzhou: [
      { label: "天河区", value: "tianhe" },
      { label: "越秀区", value: "yuexiu" },
      { label: "海珠区", value: "haizhu" }
    ],
    shenzhen: [
      { label: "南山区", value: "nanshan" },
      { label: "福田区", value: "futian" },
      { label: "罗湖区", value: "luohu" }
    ]
  };
  return districtMap[formData.city] || [];
});

// 省份变化
const handleProvinceChange = () => {
  formData.city = "";
  formData.district = "";
};

// 城市变化
const handleCityChange = () => {
  formData.district = "";
};

// LOGO上传前检查
const beforeLogoUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error('LOGO只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('LOGO大小不能超过 2MB!');
    return false;
  }
  return true;
};

// LOGO上传成功
const handleLogoSuccess = (response: any) => {
  formData.logo = response.url;
};

// LOGO文件变化
const handleLogoChange = (file: any) => {
  if (file.raw) {
    const reader = new FileReader();
    reader.onload = (e) => {
      formData.logo = e.target?.result as string;
    };
    reader.readAsDataURL(file.raw);
  }
};

// 营业执照上传前检查
const beforeLicenseUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isValidType) {
    ElMessage.error('营业执照只能是 JPG/PNG/PDF 格式!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('营业执照大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 营业执照上传成功
const handleLicenseSuccess = (response: any) => {
  formData.businessLicense = response.url;
};

// 营业执照文件变化
const handleLicenseChange = (file: any) => {
  if (file.raw) {
    formData.businessLicense = "uploaded";
    formData.businessLicenseName = file.name;
  }
};

// 移除营业执照
const removeLicense = () => {
  formData.businessLicense = "";
  formData.businessLicenseName = "";
};

// 身份证上传前检查
const beforeIdUpload: UploadProps['beforeUpload'] = (file) => {
  const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
  const isLt3M = file.size / 1024 / 1024 < 3;

  if (!isValidType) {
    ElMessage.error('身份证只能是 JPG/PNG 格式!');
    return false;
  }
  if (!isLt3M) {
    ElMessage.error('身份证大小不能超过 3MB!');
    return false;
  }
  return true;
};

// 身份证上传成功
const handleIdSuccess = (response: any) => {
  formData.idCard = response.url;
};

// 身份证文件变化
const handleIdChange = (file: any) => {
  if (file.raw) {
    formData.idCard = "uploaded";
    formData.idCardName = file.name;
  }
};

// 移除身份证
const removeIdCard = () => {
  formData.idCard = "";
  formData.idCardName = "";
};

// 返